package com.fhao.java_gobang.controller;

import com.fhao.java_gobang.constant.Constants;
import com.fhao.java_gobang.model.Result;
import com.fhao.java_gobang.model.User;
import com.fhao.java_gobang.service.UserService;
import com.fhao.java_gobang.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String username, String password) {
        //1.参数校验
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        //2.通过用户名拿到用户信息
        User user = userService.selectByName(username);
        if(user == null) {
            return Result.fail("账号不存在");
        }
        //3.进行密码校验
        if(!password.equals(user.getPassword())) {
            return Result.fail("密码错误");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,user.getUerId());
        claim.put(Constants.TOKEN_USERNAME,user.getUserName());
        String token = JwtUtils.genJwt(claim);
        return Result.success(token);
    }

    @RequestMapping("/register")
    public Result register(String username,String password) {
        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        boolean result = userService.insert(user);
        return Result.success(result);
    }

    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        log.info("getUserInfo 获取登录用户的信息");
        //从header中获取token.
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户的id
        Integer id = JwtUtils.getIdByToken(token);
        log.info("获取当前的用户id: {}",id);
        if(id == null) {
            log.info("getUserInfo 获取用户id失败");
            return Result.fail("获取用户id失败");
        }
        User user = userService.selectById(id);
        if(user == null) {
            log.info("getUserInfo 获取用户信息失败");
            return Result.fail("user为空");
        }
        user.setPassword("");
        return Result.success(user);
    }
}




















